/*
 *  Copyright 2008-2010 www.jrails.org
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.rails.core.model.attribute;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.rails.core.model.ActiveRecord;

public final class StringAttribute extends AttributeBase {

	private String value;

	public StringAttribute(final ActiveRecord record,final String name) {
		super(record, name);
	}

	@Override
	public void validate() throws AttributeException {
		if (isTrim())
			this.value = (inputValue == null) ? null : inputValue.toString().trim();
		else
			this.value = (inputValue == null) ? null : inputValue.toString();		


		if (isEmpty(this.value)) {
			this.value = getDefaultValue();
		}
		if (require && isEmpty(this.value)) {
			throwAttRequireError();
		}

		checkRange();
		if (!isEmpty(this.value) && !isEmpty(config.get(getKey(FORMAT_KEY))))
			checkFormat();

		if (unique)
			checkUnique();
	}

	@Override
	public boolean isTrim() {
		return Boolean.parseBoolean(config.get(getKey(TRIM_KEY)));
	}

	@Override
	public String getValue() {
		return value;
	}

	@Override
	public String getDefaultValue() {
		if (!containsKey(DEFAULT_KEY))
			return null;
		else
			return get(DEFAULT_KEY);
	}

	@Override
	public Integer getMin() {
		if (isEmpty(get(MIN_KEY))) {
			return null;
		} else {
			return Integer.parseInt(get(MIN_KEY));
		}
	}

	@Override
	public Integer getMax() {
		if (isEmpty(get(MAX_KEY))) {
			return null;
		} else {
			return Integer.parseInt(get(MAX_KEY));
		}
	}

	private void checkFormat() throws AttributeException {
		Pattern p = Pattern.compile(format);
		Matcher m = p.matcher(value.toString());
		if (!m.matches()) {
			throwAttFormatError();
		}
	}

	private void checkRange() throws AttributeException {
		if (getMin() != null && !isEmpty(this.value)
				&& value.length() < getMin().intValue()) {
			throwAttMinError();
		}
		if (getMax() != null && !isEmpty(this.value)
				&& value.length() > getMax().intValue()) {
			throwAttMaxError();
		}
	}

	@Override
	public Object parse(Object arg) {
		return arg;
	}

	@Override
	public String format(Object arg) {
		return "";
	}

}
